package com.birdcage.gamemanagers;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Vector;

import com.badlogic.gdx.Gdx;
import com.birdcage.gamemanagers.GameObject.EGameObjectType;

///Singleton
///It will manage all game objects.
public class GameObjectManager
{
    ///Singleton Implement
    static public GameObjectManager GetInstance()
    {
        if (m_instance == null)
        {
            m_instance = new GameObjectManager();
        }       
        return m_instance;
    }  
    
    private GameObjectManager(){};
    private static GameObjectManager m_instance = null;
    
    
    ///Public Method
    
    public void RegisterGameObject(GameObject obj)
    {
        EGameObjectType objectType = obj.GetType();
        int subType = obj.GetSubType();
        if (m_objects.containsKey(objectType) == false)
        {
            m_objects.put(objectType, new HashMap<Integer, Vector<GameObject>>());
        }
        HashMap<Integer, Vector<GameObject>> subList = m_objects.get(objectType);
        if (subList.containsKey(subType) == false)
        {
            subList.put(subType, new Vector<GameObject>());
        }
        subList.get(subType).add(obj);
    }
    
    public void Update()
    {        
        Iterator<Entry<EGameObjectType, HashMap<Integer, Vector<GameObject>>>> iter = m_objects.entrySet().iterator();
        while (iter.hasNext()) 
        {
            HashMap.Entry<EGameObjectType, HashMap<Integer, Vector<GameObject>>> entry = (HashMap.Entry<EGameObjectType, HashMap<Integer, Vector<GameObject>>>) iter.next();
            HashMap<Integer, Vector<GameObject>> objects = (HashMap<Integer, Vector<GameObject>>)entry.getValue();
            Iterator<Entry<Integer, Vector<GameObject>>> iterEx = objects.entrySet().iterator();
            while (iterEx.hasNext())
            {
                HashMap.Entry<Integer, Vector<GameObject>> entryEx = (HashMap.Entry<Integer, Vector<GameObject>>) iterEx.next();
                Vector<GameObject> objectVec = (Vector<GameObject>) entryEx.getValue();
                for(int i = 0; i < objectVec.size(); ++i)
                {
                    GameObject obj = objectVec.get(i);
                    // only update active object.
                    if (obj.GetActive())
                    {
                        objectVec.get(i).Update(GetDeltaTime());
                    }                    
                }
            }
        } 
    }
    
    public float GetDeltaTime()
    {
        //simulate 60 fps.
        return 0.016f;
        //return Gdx.graphics.getDeltaTime();
    }
    
    ///Private Members
    
    private HashMap<EGameObjectType, HashMap<Integer, Vector<GameObject>>>  m_objects = new HashMap<EGameObjectType, HashMap<Integer, Vector<GameObject>> >();
    
}
